package tools

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

// HttpPostForm 发送http post请求数据为form
func HttpPostForm(url string, data url.Values) (string, error) {
	resp, err := http.PostForm(url, data)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
	// data := url.Values{}
	// data.Set("phone", phone)
	// data.Set("password", password)
	// res, err := PostForm("/xxxxxxx", data)
}

func HttpPost(url, postData string, headers map[string]string) (responseData string, err error) {
	request, _ := http.NewRequest("POST", url, strings.NewReader(postData))
	if headers["Content-Type"] == "" {
		headers["Content-Type"] = "application/json"
	}
	if headers["Accept"] == "" {
		headers["Accept"] = "application/json"
	}
	for key, val := range headers {
		request.Header.Add(key, val)
	}
	resp, err := http.DefaultClient.Do(request) // 发送请求
	defer resp.Body.Close()
	if err != nil {
		return
	} else {
		byteData, err2 := io.ReadAll(resp.Body)
		if err2 != nil {
			err = err2
			return
		}
		responseData = string(byteData)
	}
	return
}

func HttpGet(reqUrl string) (respBody []byte, err error) {
	resp, err := http.Get(reqUrl) //发起get请求
	if err != nil {
		return
	}
	defer resp.Body.Close()               //关闭请求
	respBody, err = io.ReadAll(resp.Body) //解析请求信息
	if err != nil {
		return
	}
	return
}
